/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Author: Shahab.Alishahian@gmail.com SA	
///////////////Target:The following methods are here to handle all GAPI functions.
///////////////Version:1.1
///////////////CopyRight: 2014 Noranj Co.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//*************************************************************************************************************
//******Facebook SDK setting

var appId='' ;
var accessToken='' ;
var appAccessToken='' ;
var channelUrl='' ;

if(window.location.href.indexOf("appspot") > -1){
	//JSITE
	appId ='538796809531275' ;
	channelUrl ='localhost' ;
	appAccessToken = '538796809531275|rXh4hMppl93RPlMc_2iITeRLHjs' ;
}
else{
	 //localhost
	appId='398847723578997' ;
	channelUrl='localhost' ;
	appAccessToken = '398847723578997|LicynEmM0LUt4dYaqH4ojjPYcBI' ;
}
//*************************************************************************************************************
//******Google APi setting 
var clientId = '913666381572.apps.googleusercontent.com'; //jb-shhb->'828062657182-a2i7dlpvhlv2uqe4f101i1430qh1thmr.apps.googleusercontent.com';
var apiKey = 'AIzaSyBrR0uxe3x6G2-ntujf9YURrfE5R9QT728'; //jb-shhb->'AIzaSyCZtTH-e9ZXKkNX07j7RzTtDttNS_JrwfQ';
var scopes = 'https://www.googleapis.com/auth/userinfo.email'; // 'https://www.googleapis.com/auth/plus.me';
var MY_API_ROOT = 'https://shhbjb.appspot.com/_ah/api';
var MY_API_VER = 'v4';
var MY_API_NAME = 'jb';

//REMOVED and moved as a direction line in site.html
//$.getScript('https://apis.google.com/js/client.js', function() {        
//	  $('body').append('<p>GOOGLE API  is loaded</p>');
//});

window.onload = function() {
    //gapi.client.setApiKey(apiKey);
    gapi.client.load(MY_API_NAME, MY_API_VER, null, MY_API_ROOT);
}

$(document).ready(function() {
 
	console.log($(".controlPlace").height());
	
	if($(".controlPlace").height()>0)
		$(".fancybox").height($(".controlPlace").height()-45);
	else
		$(".fancybox").height(500);
	
	//Loading first dialog in main place./
	loadparts(1);
	
	 var myVar = setTimeout(function(){
		    var p = $( "#contentHolder" );
			var position = p.offset();
			var width = p.width() - 54;
			$('#box' + ($('#stepvalue').val())).animate({ 'right': position.left-1,'top': position.top, 'width':width}, 1000);
	 },1000);
	  

	
 window.fbAsyncInit = function () {
	
     FB.init({
         appId: appId, // App ID
         channelUrl: channelUrl, // Channel File
         status: true, // check login status
         cookie: true, // enable cookies to allow the server to access the session
         xfbml: true, // parse XFBML
         frictionlessRequests : true
     });
 };
 // Load the SDK Asynchronously
 (function (d) {
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {
         return;
     }
     js = d.createElement('script');
     js.id = id;
     js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
 } (document));
});

 function loggedin() {
	    FB.getLoginStatus(function (response) {
	    	//alert(response.status );
	    	loadparts(2);
	        if (response.status === 'connected') {
	            FB.api('/me', function (user) {
	                if (!($("#fbid").val()) && ($("#UserName").val())) {
	                    alert('Authentication Failed!');
	                }
	                else {
	                	//user.id = 824750206; //TODO:SA:Must be removed after testing.
	                    $("#fbid").val(user.id);
	                    $("#firstName").val(user.first_name);
	                    $("#lastName").val(user.last_name);
	                    $("#userName").val(user.email);
	                    $("#emailAddress").val(user.email);
	                    $("#userImage").attr("src",'https://graph.facebook.com/' + user.id + '/picture?width=155&Height=170');
	                    addUser(user);
	                }
	            });
	        }
	    });
	}
 
 function loadparts(index){
	 if(index === 1)
		$("#laodingPlace").load("htc/loginpart.html"); 
	 else if(index === 2)
		$("#boardSelectorPlace").load("htc/listofboards.html");
	 else if(index === 3)
		$("#boardConversationPlace").load("htc/boardconversation.html");
	 else if(index === 4){
		 $("#adminPanelPlace").load("htc/adminpanel.html");
	 }
 }
 
 //$('[id^="btnNext"]').click(function(){
	 function bringNext(step){
		var p = $( "#contentHolder" );
		var position = p.offset();
		var width= p.width() - 54;
		$('#box' + document.getElementById("stepvalue").value).animate({ 'left': '-1500px' },1000);
		if(step==undefined)
			$('#stepvalue').val(parseInt($('#stepvalue').val()) + 1);
		else
			$('#stepvalue').val(step);
	    
		loadparts($('#stepvalue').val());
	    $('#box' + ($('#stepvalue').val())).animate({ 'right': position.left-1,'top': position.top, 'width':width}, 1000);
	    
	}
//************************************************************************************************************
	 function addUser(user){
			
			var tempdata = {};
			tempdata['address'] = '0';
			tempdata['age'] = '0';
			tempdata['city'] = '0';
			tempdata['country'] = '0';
			tempdata['dateCreated'] = returnToday();
			tempdata['email'] = user.email;
			tempdata['facebookId'] = user.id;
			tempdata['firstName'] = user.first_name;
			tempdata['gender'] = '0';
			tempdata['lastName'] = user.last_name;
			tempdata['merchantId'] = $("#jbMerchantId").val();
			setAddUser(tempdata);
		}

	 
//*************************************************************************************************************
function getQueryStringParams(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
  }

//*************************************************************************************************************
function returnToday(){
	  var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth()+1;
      var yyyy = today.getFullYear();
      
      if(dd<10){dd='0'+dd;} 
      if(mm<10){mm='0'+mm;}
      
      var returnToday = yyyy + '' + mm +'' + dd ;
      delete yyyy;
      delete mm;
      delete dd;
      return returnToday;
}

//*************************************************************************************************************
function addConversations(idDiscussion,dataDiscussion,objectHolder){
	var data = {};
	data["id"] = idDiscussion;
	data["discussion"] = dataDiscussion.discussion;
	data["status"] = dataDiscussion.status;
	
	var contributer = {};
	contributer["id"] = $("#jsUserId").val();
	contributer["firstName"] = $("#firstName").val();
	contributer["lastName"] = $("#lastName").val();
	contributer["facebookId"] = $("#fbid").val();
	
	$(objectHolder).append(createConversation(data,contributer));
}
//*************************************************************************************************************
function sendMessage(to,text) {
    FB.getLoginStatus(function (response) {
        FB.ui({
                 method: "send",
                 app_id:appId,
                 to:to,
                 picture: $('#jsSelectedImageURL').val(),
                 link: $('#jsSelectedBoardURL').val(),
                 description:text,
                 name: text,
                 display: 'popup'
             },
             function (param) {
                 console.log('done');
            });
         });
  }


function sendANotification(contactId,senderId,notifyText,url,imageUrl) {
    //var param = 'https://apps.facebook.com/'+ appId +'/fb_source=myapps' ;
    var param = '?url_id=' + encodeURIComponent(url) + '&url_image=' + encodeURIComponent(imageUrl);
    //var strUrl = 'https://graph.facebook.com/'+ contactId +'/notifications?access_token=' + appAccessToken + '&href=' + param + '&template= @['+senderId+'] ' +   notifyText
    var strUrl = 'https://graph.facebook.com/'+ contactId +'/notifications';
    FB.getLoginStatus(function (response) {
      $.ajax({ type: 'POST',
          url:strUrl,
          data: {
              href: param,
              access_token: appAccessToken ,
              template: ' @['+senderId+'] ' + notifyText
          },
          success: function (response) {
              console.log(response);
          },
          error: function(error) {
          	console.log(error);
          }
      });
    });
  }
     